package com.example.sid.data

import android.content.Context
import android.content.SharedPreferences
import com.example.sid.ui.app.App
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write

object LocalStorage {

	private val sp: SharedPreferences by lazy {
		App.context.getSharedPreferences(
			App.context.packageName + "LocalStorage",
			Context.MODE_PRIVATE
		)
	}
	
	private val prefLock = ReentrantReadWriteLock()
	private var saveJob: Job? = null
	fun saveData(){
		saveJob?.cancel()
		saveJob = CoroutineScope(Dispatchers.IO).launch {
			delay(100)
			prefLock.write {
				sp.edit()?.putString("partnerID", ValueRamStorage.partnerID)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerName", ValueRamStorage.partnerName)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerProfileURL", ValueRamStorage.partnerProfileURL)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerUrlRedirectText", ValueRamStorage.partnerUrlRedirect)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerScope", ValueRamStorage.partnerScope)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerState", ValueRamStorage.partnerState)?.apply()
			}
			prefLock.write {
				sp.edit()?.putString("partnerNonce", ValueRamStorage.partnerNonce)?.apply()
			}
			prefLock.write {
				sp.edit()?.putBoolean("isShowError", ValueRamStorage.isShowError)?.apply()
			}
		}
	}

	fun loadData(){
		prefLock.read {
			ValueRamStorage.partnerID = sp.getString("partnerID", "").toString()
			ValueRamStorage.partnerName = sp.getString("partnerName", "").toString()
			ValueRamStorage.partnerProfileURL = sp.getString("partnerProfileURL", "").toString()
			ValueRamStorage.partnerUrlRedirect = sp.getString("partnerUrlRedirectText", "").toString()
			ValueRamStorage.partnerScope = sp.getString("partnerScope", "").toString()
			ValueRamStorage.partnerState = sp.getString("partnerState", "").toString()
			ValueRamStorage.partnerNonce = sp.getString("partnerNonce", "").toString()
			ValueRamStorage.isShowError = sp.getBoolean("isShowError", false) ?: false
		}
	}
}